package org.ly.uap.client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.TimeZone;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ly.uap.client.proxy.ProxyGrantingTicketStorage;
import org.ly.uap.client.validation.ProxyList;
import org.ly.uap.client.validation.ProxyListEditor;

public final class CommonUtils {
    private static final Log LOG = LogFactory.getLog(CommonUtils.class);
    private static final String PARAM_PROXY_GRANTING_TICKET_IOU = "pgtIou";
    private static final String PARAM_PROXY_GRANTING_TICKET = "pgtId";

    public static String formatForUtcTime(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return dateFormat.format(date);
    }

    public static void assertNotNull(Object object, String message) {
        if (object == null)
            throw new IllegalArgumentException(message);
    }

    public static void assertNotEmpty(Collection<?> c, String message) {
        assertNotNull(c, message);
        if (c.isEmpty())
            throw new IllegalArgumentException(message);
    }

    public static void assertTrue(boolean cond, String message) {
        if (!cond)
            throw new IllegalArgumentException(message);
    }

    public static boolean isEmpty(String string) {
        return (string == null) || (string.length() == 0);
    }

    public static boolean isNotEmpty(String string) {
        return !isEmpty(string);
    }

    public static boolean isBlank(String string) {
        return (isEmpty(string)) || (string.trim().length() == 0);
    }

    public static boolean isNotBlank(String string) {
        return !isBlank(string);
    }

    public static String constructRedirectUrl(String casServerLoginUrl, String serviceParameterName, String serviceUrl, boolean renew, boolean gateway) {
        try {
            return casServerLoginUrl + (casServerLoginUrl.indexOf("?") != -1 ? "&" : "?") + serviceParameterName + "=" +
                    URLEncoder.encode(serviceUrl, "UTF-8") + (
                    renew ? "&renew=true" : "") + (
                    gateway ? "&gateway=true" : "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

    }

    public static void readAndRespondToProxyReceptorRequest(HttpServletRequest request, HttpServletResponse response, ProxyGrantingTicketStorage proxyGrantingTicketStorage) throws IOException {
        String proxyGrantingTicketIou = request.getParameter("pgtIou");

        String proxyGrantingTicket = request.getParameter("pgtId");

        if ((isBlank(proxyGrantingTicket)) || (isBlank(proxyGrantingTicketIou))) {
            response.getWriter().write("");
            return;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Received proxyGrantingTicketId [" +
                    proxyGrantingTicket + "] for proxyGrantingTicketIou [" +
                    proxyGrantingTicketIou + "]");
        }

        proxyGrantingTicketStorage.save(proxyGrantingTicketIou, proxyGrantingTicket);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Successfully saved proxyGrantingTicketId [" +
                    proxyGrantingTicket + "] for proxyGrantingTicketIou [" +
                    proxyGrantingTicketIou + "]");
        }

        response.getWriter().write("<?xml version=\"1.0\"?>");
        response.getWriter().write("<casClient:proxySuccess xmlns:casClient=\"http://www.yale.edu/tp/casClient\" />");
    }

    public static String constructServiceUrl(HttpServletRequest request, HttpServletResponse response, String service, String serverName, String artifactParameterName, boolean encode) {
        if (isNotBlank(service)) {
            return encode ? response.encodeURL(service) : service;
        }

        StringBuilder buffer = new StringBuilder();

        if ((!serverName.startsWith("https://")) && (!serverName.startsWith("http://"))) {
            buffer.append(request.isSecure() ? "https://" : "http://");
        }

        buffer.append(serverName);
        buffer.append(request.getRequestURI());

        if (isNotBlank(request.getQueryString())) {
            int location = request.getQueryString().indexOf(artifactParameterName + "=");

            if (location == 0) {
                String returnValue = encode ? response.encodeURL(buffer.toString()) : buffer.toString();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("serviceUrl generated: " + returnValue);
                }
                return returnValue;
            }

            buffer.append("?");

            if (location == -1) {
                buffer.append(request.getQueryString());
            } else if (location > 0) {
                int actualLocation = request.getQueryString()
                        .indexOf("&" + artifactParameterName + "=");

                if (actualLocation == -1)
                    buffer.append(request.getQueryString());
                else if (actualLocation > 0) {
                    buffer.append(request.getQueryString().substring(0,
                            actualLocation));
                }
            }
        }

        String returnValue = encode ? response.encodeURL(buffer.toString()) : buffer.toString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("serviceUrl generated: " + returnValue);
        }
        return returnValue;
    }

    public static String safeGetParameter(HttpServletRequest request, String parameter) {
        if (("POST".equals(request.getMethod())) && ("logoutRequest".equals(parameter))) {
            LOG.debug("safeGetParameter called on a POST HttpServletRequest for LogoutRequest.  Cannot complete check safely.  Reverting to standard behavior for this Parameter");
            return request.getParameter(parameter);
        }
        return (request.getQueryString() == null) || (request.getQueryString().indexOf(parameter) == -1) ? null : request.getParameter(parameter);
    }

    public static String getResponseFromServer(URL constructedUrl, String encoding) {
        return getResponseFromServer(constructedUrl, HttpsURLConnection.getDefaultHostnameVerifier(), encoding);
    }

    public static String getResponseFromServer(URL constructedUrl, HostnameVerifier hostnameVerifier, String encoding) {
        if(HttpRemote.isEnabledFlag()){
            System.out.println("ly-uap url:" + constructedUrl.getPath());
            return HttpRemote.getResponseFromServer(constructedUrl, hostnameVerifier, encoding);
        }
        URLConnection conn = null;
        try {
            conn = constructedUrl.openConnection();
            if ((conn instanceof HttpsURLConnection))
                ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
            BufferedReader in;
            if (isEmpty(encoding))
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            else {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
            }

            StringBuilder stringBuffer = new StringBuilder(255);
            String line;
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            String str1 = stringBuffer.toString();
            return str1;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            if ((conn != null) && ((conn instanceof HttpURLConnection)))
                ((HttpURLConnection) conn).disconnect();
        }
    }

    public static String getResponseFromServer(String url, String encoding) {
        try {
            return getResponseFromServer(new URL(url), encoding);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException(e);
        }

    }

    public static ProxyList createProxyList(String proxies) {
        if (isBlank(proxies)) {
            return new ProxyList();
        }

        ProxyListEditor editor = new ProxyListEditor();
        editor.setAsText(proxies);
        return (ProxyList) editor.getValue();
    }

    public static void sendRedirect(HttpServletResponse response, String url) {
        try {
            response.sendRedirect(url);
        } catch (Exception e) {
            LOG.warn(e.getMessage(), e);
        }
    }
}

/* Location:           D:\work\szdj\EasyConnectInstaller\ly-uap-3.2.0.jar
 * Qualified Name:     org.ly.uap.client.util.CommonUtils
 * JD-Core Version:    0.6.0
 */
